public class Solution993 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int deepX=-1,deepY=-1;
    boolean ans=true;

    public boolean isCousins(TreeNode root, int x, int y) {
        dfs(root,0,x,y);
        return ans && deepX==deepY;
    }

    void dfs(TreeNode root,int deep,int x,int y){
        if (root==null){
            return;
        }
        if (root.val==x){
            deepX=deep;
        }
        if (root.val==y){
            deepY=deep;
        }
        if (root.left!=null && root.right!=null && root.left.val+root.right.val==x+y && root.left.val*root.right.val==x*y){
            ans=false;
        }
        dfs(root.left,deep+1,x,y);
        dfs(root.right,deep+1,x,y);
    }

    public static void main(String[] args) {
        TreeNode treeNode=new TreeNode(1,new TreeNode(2,new TreeNode(4),null),new TreeNode(3));
        System.out.println(new Solution993().isCousins(treeNode,4,3));
    }
}
